package cn.itsource.basic.service.impl;

import cn.itsource.basic.mapper.BaseMapper;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.service.IBaseService;
import cn.itsource.basic.util.PageBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//默认required
public class BaseServiceImpl<T> implements IBaseService<T> {

    @Autowired
    BaseMapper<T> mapper;

    @Override
    @Transactional
    public boolean add(T t) {
        return mapper.add(t)>0;
    }

    @Override
    @Transactional
    public boolean update(T t) {
        return mapper.update(t)>0;
    }

    @Override
    @Transactional
    public boolean del(Long id) {
        return mapper.del(id)>0;
    }

    @Override
    @Transactional
    public boolean batchRemove(List<Long> id) {
        return mapper.batchRemove(id)>0;
    }

    @Override
    public T findById(Long id) {
        return mapper.findById(id);
    }

    @Override
    public List<T> findAll() {
        return mapper.findAll();
    }

    @Override
    public PageBean<T> findByPage(BaseQuery query) {
        //1.使用PageHelper设置当前页和每页显示的记录数
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        //2.调用mapper层查询数据 data
        List<T> rows = mapper.findByCondions(query);
        //3.拿查到的记录构建pageInfo对象
        PageInfo<T> info = new PageInfo<>(rows);
        //4.根据构建pageInfo对象拿到总记录数
        long total = info.getTotal();
        //5.构建PageBean返回
        PageBean<T> pageBean = new PageBean<>();
        pageBean.setTotals(total);
        pageBean.setRows(rows);
        return pageBean;
    }


}
